// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const timeutil = require('./timeutil');
const COUPLES = 'cloud-user-couples';
const USER = 'edu-cloud-users'
const _ = db.command;
// 云函数入口函数

if (!Promise.allSettled) {
    const rejectHandler = reason => ({
        status: "rejected",
        reason
    })
    const resolveHandler = value => ({
        status: "fulfilled",
        value
    })
    Promise.allSettled = promises =>
        Promise.all(
            promises.map((promise) =>
                Promise.resolve(promise)
                .then(resolveHandler, rejectHandler)
            )
            // 每个 promise 需要用 Promise.resolve 包裹下
            // 以防传递非 promise
        );
}
async function execPromise(tasks) {
    return new Promise(function (resolve, reject) {
        Promise.all(tasks).then(res => {
            resolve(res)
            reject(res)
        })
    })
}
async function execPromiseSettled(tasks) {
    return new Promise(function (resolve, reject) {
        Promise.allSettled(tasks).then(res => {
            resolve(res)
            reject(res)
        })
    })
}
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    /**获取操作类型 */
    let action = event.action;
    /**获取小程序用户唯一身份识别ID */
    let openid = event.openid || wxContext.OPENID;
    /**获取对方唯一身份识别ID */
    let bindId = event.bindId;
    /**根据ID 查询受邀用户是否已绑定信息 */
    let userBase = {};
    let queryRes = await db.collection(USER).where({
        openid
    }).get();
    /**查询对应的数据 */
    if (queryRes.data.length == 0) {
        return {
            errCode: -1,
            errMsg: '暂未绑定学号信息',
        }
    } else {
        userBase = queryRes.data[0]
    }
    switch (action) {
        /**取消关联 */
        case 'unlinkCouple':{
            return await db.collection(COUPLES).where(_.or([
                {
                    theone:userBase._id
                },
                {
                    theeach:userBase._id
                }
            ])).remove();
            break
        }
        case 'findCouple':{
            //查询自己的情侣信息
            let CoupleRes = await db.collection(COUPLES).where({
                theone:userBase._id
            }).get(); 
            if(CoupleRes.data.length == 0){
                return {
                    errCode:-1,
                    errMsg:'没有情侣信息'
                }
            }else{
                let coupleTmp = CoupleRes.data[0];
                let otherBase = {};
                /**查询对方信息 */
                try {
                    let otherTmp = await db.collection(USER).doc(coupleTmp.theeach).get();
                    otherBase = otherTmp.data;
                } catch (error) {
                    return {
                        errCode:-1,
                        errMsg:'未查询到情侣具体信息'
                    }
                }
                return {
                    userBase,
                    otherBase,
                    coupleId:otherBase._id
                }
            }
            break
        }
        case 'bindCouple': {
            /**查询绑定ID对应的用户信息 */
            let eachBase = {};
            try {
                eachBase = await db.collection(USER).doc(bindId).get().data;
            } catch (error) {
                return {
                    errCode: -1,
                    errMsg: '未查询到绑定用户信息'
                }
            }
            /**查询是否已经绑定情侣信息 */
            //1. 查询自己是否绑定了情侣信息
            let selfCoupleRes = await db.collection(COUPLES).where({
                theone: userBase._id
            }).get();
            if (selfCoupleRes.data.length > 0) {
                let coupleTmp = selfCoupleRes.data[0];
                return {
                    errCode: -1,
                    errMsg: '不可重复绑定情侣关系'
                }
            }
            //2. 查询对方是否已经绑定了情侣关系
            let otherCoupleRes = await db.collection(COUPLES).where({
                theone: bindId
            }).get();
            if (otherCoupleRes.data.length > 0) {
                return {
                    errCode: -1,
                    errMsg: '对方已绑定情侣关系'
                }
            }
            /**执行写入操作 */
            let promiseTasks = [];
            promiseTasks.push(db.collection(COUPLES).add({
                data: {
                    theone: userBase._id,
                    theeach: bindId,
                    bindDate: timeutil.TimeCodeYmd()
                }
            }))
            promiseTasks.push(db.collection(COUPLES).add({
                data: {
                    theone: bindId,
                    theeach: userBase._id,
                    bindDate: timeutil.TimeCodeYmd()
                }
            }))
            return await execPromiseSettled(promiseTasks);
            break
        }
    }

}